package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Cart;
import com.itheima.reggie.mapper.CartMapper;
import com.itheima.reggie.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    @Override
    public Cart add(Cart cartParam) {
        //查询当前菜品/套餐在数据表中是否已存在
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, UserHolder.get().getId());
        wrapper.eq(cartParam.getDishId() != null, Cart::getDishId, cartParam.getDishId());
        wrapper.eq(cartParam.getSetmealId() != null, Cart::getSetmealId, cartParam.getSetmealId());
        Cart cart = cartMapper.selectOne(wrapper);
        if (cart != null) {
            //当前菜品/套餐在数据表中已存在、number+1
            cart.setNumber(cart.getNumber() + 1);
            cartMapper.updateById(cart);

            return cart;
        } else {
            //不存在，UserId     number=1  createTime
            cartParam.setUserId(UserHolder.get().getId());
            cartParam.setNumber(1);
            cartParam.setCreateTime(new Date());

            cartMapper.insert(cartParam);
            return cartParam;
        }
    }

    @Override
    public List<Cart> findList() {
        //设置查询条件
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, UserHolder.get().getId());
        wrapper.orderByAsc(Cart::getCreateTime);
        List<Cart> cartList = cartMapper.selectList(wrapper);


        return cartList;
    }




    @Override
    public void clean() {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, UserHolder.get().getId());
        cartMapper.delete(wrapper);
    }

    @Override
    public Cart update(Cart cartParam) {
        //确定更新的购物车
        Long dishId = cartParam.getDishId();
        Long setmealId = cartParam.getSetmealId();

        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(dishId != null, Cart::getDishId, dishId);
        wrapper.eq(setmealId != null, Cart::getSetmealId, setmealId);
        Cart cart = cartMapper.selectOne(wrapper);

        //执行操作
        if (cart != null) {
            cart.setNumber(cart.getNumber() - 1);
            if (cart.getNumber() <= 0) {
                cartMapper.deleteById(cart);
            } else {
                cartMapper.updateById(cart);
            }
        }
        return cart;
    }


}
